import { ChangeDetectorRef, Component } from '@angular/core';
 

import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzDescriptionsModule } from 'ng-zorro-antd/descriptions';
import { NzPageHeaderModule } from 'ng-zorro-antd/page-header';
import { NzSpaceModule } from 'ng-zorro-antd/space';
import { NzStatisticModule } from 'ng-zorro-antd/statistic';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { NzDividerModule} from 'ng-zorro-antd/divider'
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { inject } from '@angular/core';

import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';

import { NzTableModule } from 'ng-zorro-antd/table';
import   DeviceInformation  from './deviceInformation'
import { NzMessageService } from 'ng-zorro-antd/message';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';


import {getDeviceListUrl,addDeviceUrl,deleteDeviceByIdUrl} from '../constant'

 
import { NzModalModule } from 'ng-zorro-antd/modal';


@Component({
  selector: 'app-device-list',
  imports: [NzButtonModule, NzDescriptionsModule,
     NzPageHeaderModule, NzSpaceModule, NzStatisticModule, 
     NzTableModule,
     NzDividerModule,
     NzModalModule,
     NzPopconfirmModule,
     NzTabsModule,NzFormModule,NzInputModule,ReactiveFormsModule],
  templateUrl: './device-list.html',
  styleUrl: './device-list.scss'
})
export class DeviceList {


  ///
  constructor(private nzMessageService: NzMessageService,private http: HttpClient,private cdr: ChangeDetectorRef) {
    this.updateDeviceList("","");
  }

  listOfData: DeviceInformation[] = [];
  private fb = inject(NonNullableFormBuilder);
  validateForm = this.fb.group({
    deviceSn: this.fb.control(''),
    deviceId: this.fb.control('')
  });

  validateFormOfAddModal = this.fb.group({
    deviceSnOfAddModal: this.fb.control(''),
    deviceIdOfAddModal: this.fb.control('')
  });

  submitForm():void{
 
  }
  trackById(index: number, item: any): number {
    return item.Id; // 确保返回唯一标识
  }
  /// 默认所有，没有优化，
  updateDeviceList(deviceSn:string,deviceId:string):void {
    
    var self=this;
    const params = new HttpParams().set('deviceSn', deviceSn)
    .set('deviceId', deviceId);

    this.http.get(getDeviceListUrl, { params })
    .subscribe({
        next(value:any) 
        {
          
          var list:[]=value.data;
          self.listOfData= list.map(function(item:any){
            return {
              Id:item.id,
              deviceId: item.deviceId,
              deviceSn:  item.deviceSn,
            }
          });
          console.log(self.listOfData.length)
          self.cdr.detectChanges()
        }
       });
  }

  ///查询
  query(): void {
    var deviceSn=this.validateForm.get("deviceSn")?.value+"";
    var deviceId=this.validateForm.get("deviceId")?.value+"";
    this.updateDeviceList(deviceSn,deviceId);
  }
  cancelDelete(): void {
    this.nzMessageService.info('删除取消');
  }
  
  ///删除
  confirmDelete(Id:number): void {
    var deviceSn=this.validateForm.get("deviceSn")?.value+"";
    var deviceId=this.validateForm.get("deviceId")?.value+"";
    var self=this;
    
    const headers = new HttpHeaders().set('Content-Type', 'application/json');
 
    this.http.post(deleteDeviceByIdUrl, JSON.stringify({Id}), { headers: headers })
    .subscribe({
        next(value:any) 
        {
        

           if (value.code==1)
            {
              self.nzMessageService.info('删除成功');
            } else{
             self.nzMessageService.warning(value.message);
            }
   
          //更新列表
           self.updateDeviceList(deviceSn,deviceId)
        }
       });

  }

  isVisibleOfAddModal = false;
  isOkLoadingOfAddModal = false;

  showAddModal(): void {
    this.isVisibleOfAddModal = true;
  }

  confirmAdd(): void {

    var self=this;
    this.isOkLoadingOfAddModal = true;

    var deviceSnOfQuery=this.validateForm.get("deviceSn")?.value+"";
    var deviceIdOfQuery=this.validateForm.get("deviceId")?.value+"";

    var deviceSn=(this.validateFormOfAddModal.get("deviceSnOfAddModal")?.value+"").trim();
    var deviceId=(this.validateFormOfAddModal.get("deviceIdOfAddModal")?.value+"").trim();

    if (deviceSn=="" ){

      this.nzMessageService.info('deviceSn 为空');
      return;
    } 
    if (deviceId==""){
      this.nzMessageService.info('deviceId 为空');
      return;
    }

      const headers = new HttpHeaders().set('Content-Type', 'application/json');

    this.http.post(addDeviceUrl,JSON.stringify({
      deviceSn,
      deviceId

    }), { headers: headers })
    .subscribe({
      next(value:any) 
      {
        self.isVisibleOfAddModal = false;
        self.isOkLoadingOfAddModal = false;
      

         self.validateFormOfAddModal.get("deviceSnOfAddModal")?.setValue("")
         self.validateFormOfAddModal.get("deviceIdOfAddModal")?.setValue("")

         if (value.code==1)
         {
          self.nzMessageService.info('新增成功');
         } else{
          self.nzMessageService.warning(value.message);
         }

       //更新列表
        self.updateDeviceList(deviceSnOfQuery,deviceIdOfQuery)
      }
     });

  }

  cancelAdd(): void {
    this.isVisibleOfAddModal = false;
  }
}